package cn.itcast.bos.service.system.impl;

import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.itcast.bos.dao.system.MenuRepository;
import cn.itcast.bos.dao.system.PermissionRepository;
import cn.itcast.bos.dao.system.RoleRepository;
import cn.itcast.bos.domain.system.Menu;
import cn.itcast.bos.domain.system.Permission;
import cn.itcast.bos.domain.system.Role;
import cn.itcast.bos.domain.system.User;
import cn.itcast.bos.service.system.RoleService;

@Service
@Transactional
public class RoleServiceImpl implements RoleService {
	@Resource
	private RoleRepository repository;
	@Resource
	private PermissionRepository permissionRepository;
	@Resource
	private MenuRepository menuRepository;

	@Override
	public List<Role> findByUser(User user) {
		if (user.getUsername().equals("bao")) {
			return repository.findAll();
		} else {
			return repository.findByUser(user.getId());
		}
	}

	@Override
	public List<Role> findAll() {
		return repository.findAll();
	}

	@Override
	public void saveRole(Role role, String[] permissionIds, String menuIds) {
		//关联权限
		if (permissionIds != null) {
			for (String permission : permissionIds) {
				Permission permission2 = permissionRepository.findOne(Integer.parseInt(permission));
				role.getPermissions().add(permission2);
			}
		}
		//关联菜单
		if (StringUtils.isNoneBlank(menuIds)) {
			String[] menidsArray = menuIds.split(",");
			for (String menuid : menidsArray) {
				Menu menu = menuRepository.findOne(Integer.parseInt(menuid));
				role.getMenus().add(menu);
			}
		}
		//保存角色
		repository.save(role);
	}

}
